#!/usr/bin/python
# -*-coding:utf-8 -*-
# use python 2.7
import RPi.GPIO as GPIO
import time  # 导入time模块
import os
import json
import urllib
import urllib2

GPIO.setmode(GPIO.BOARD)    #gpio采用board编号
GPIO.setup(7, GPIO.IN)
temp = 0  # 温度变量
fan = "0"  # 循环变量

def get_token():
	apiKey = "Aoz1wQwMpnMTAvjMU74eItvA"
	secretKey = "84be0fbcb12692ab55daced0aa43cb4e"

	auth_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + apiKey + "&client_secret=" + secretKey;  

	res = urllib2.urlopen(auth_url)
	json_data = res.read()
#	print json_data
	return json.loads(json_data)['access_token']
	
while (1):  # 此处设置循环
	file = open( "/sys/class/thermal/thermal_zone0/temp" )  # 打开CPU温度缓存文件
	temp = float( file.read( ) ) / 1000  # 读取结果，并转换为浮点数/1000
	file.close( )  # 关闭文件
	
	if (temp > 50 and fan == "0"):  # 如果>50C
		GPIO.setup(7, GPIO.OUT, initial=GPIO.LOW) #7口输出
		fan = "1"
		os.system ('mplayer fanison.mp3')
	elif(temp < 40 and fan == "1" ):    #如果小于40度
		GPIO.setup(7, GPIO.IN)  #7口输入，就是不输出了呗，因为高电平低电平都能驱动三极管。
		fan = "0"
		os.system ('mplayer fanisoff.mp3')
	timenow = time.strftime( "%H:%M:%S", time.localtime( ) )  # 时间
	print timenow + ": %.1f" % temp + "C FAN = " + fan  # 时间+温度
	#token = get_token()
	#texta = "现在的CPU温度是" + str(temp) + "度"
	#textb = urllib.quote(texta)
	#url = "http://tsn.baidu.com/text2audio?tex="+textb+"&lan=zh&per=0&pit=1&spd=5&cuid=8466761&ctp=1&tok="+token
	#os.system('mplayer "%s"'%(url))
	time.sleep(10)  # 间隔10秒

#GPIO.cleanup()
#print "Over"    #跳出循环结束
#000000000
